//导入模型
const{
    createNoteBook,
    searchNoteBook,
    updateNoteBook,
}=require(process.cwd()+'/model/note_model.js');
const url = require('url');
const querystring = require('querystring');
const fs = require('fs');
global.text='';
//定义处理方法
const create= (req,res)=>{
    let data = '';
    req.on('data', chunk => {
        data += chunk;
    })
    req.on('end',()=>{
        let rs=createNoteBook(JSON.parse(data));
        if(!rs){
            console.log('error');
        }
    });

}
const update= async(req,res)=>{
    let books= await searchNoteBook();
    let titles=[];
    books.forEach((item)=>{
        titles.push({'title':item.title});
    })
    res.writeHead(200,'o98k',{'content-type':'text/plain;charset=utf-8'});
    res.end(JSON.stringify(titles));
}
const openNotebook=async(req,res)=>{
    let arr = req.url.split('?');
    let url = querystring.parse(arr[1]);//即得到JSON形式的数据。
    let target={
        'title':url.title,
    };
    let target_book=await searchNoteBook(target);
    res.writeHead(200,'o98k',{'content-type':'text/plain;charset=utf-8'});
    res.end(JSON.stringify(target_book));
}
const addNote=(req,res)=>{
    let data = '';
    req.on('data', chunk => {
        data += chunk;
    })
    req.on('end',()=>{
        let new_note=JSON.parse(data);
        let url=new_note['url'];
        delete new_note.url;
        let arr = url.split('?');
        let book_title = querystring.parse(arr[1])['book_title'];
        //开始查询并修改数据库
        let target_book;
        let promise=new Promise(async(resolve,reject)=>{
            target_book=await searchNoteBook({'title':book_title});
            resolve('find_success');
        }).then(()=>{
            let after=target_book[0];
            if(after['contents']===undefined){
                let temp=[new_note];
                after.contents=temp;
            }
            else after.contents.push(new_note)
            updateNoteBook({'title':book_title},after);
        })
        
    });
}
const viewNote=async(req,res)=>{
    let arr = req.url.split('?');
    let url = querystring.parse(arr[1]);
    let book_title=url.book_title;
    let note_title=url.note_title;
    let rc=await searchNoteBook({title:book_title});
    let notes=rc[0]['contents'];
    notes.forEach((item)=>{
        if(item.title===note_title){
            res.end(item.text);
        }
    })
}
const modifyNote=(req,res)=>{
    let data = '';
    req.on('data', chunk => {
        data += chunk;
    })
    req.on('end',()=>{
        let existing_note=JSON.parse(data);
        let book_title=existing_note['book_title'];
        delete existing_note.book_title;
        //开始查询并修改数据库
        let target_book;
        let promise=new Promise(async(resolve,reject)=>{
            target_book=await searchNoteBook({'title':book_title});
            resolve('find_success');
        }).then(()=>{
            let after=target_book[0];
            for(let i=0;i<after.contents.length;++i){
                if(after.contents[i].title===existing_note.title){
                    after.contents[i]=existing_note;
                    break;
                }
            }
            updateNoteBook({'title':book_title},after);
        })
        
    });
}
const findNote=(req,res)=>{
    let arr = req.url.split('?');
    let url = querystring.parse(arr[1]);
    let book_title=url.book_title;
    let note_title=url.note_title;
    let target_book;
    res.writeHead(200,'o98k',{'content-type':'text/plain;charset=utf-8'});
    let promise=new Promise(async(resolve,reject)=>{
        target_book=await searchNoteBook({'title':book_title});
        resolve('find_success');
    }).then(()=>{
        let after=target_book[0];
        if(after['contents']===undefined){
            res.end('');
        }
        else{
            for(let i=0;i<after.contents.length;++i){
                if(after.contents[i].title===note_title){
                    res.end(JSON.stringify({title:"ok"}));
                }
            }
            res.end('');
        }
    })
}
const initNote=async(book_title,note_title)=>{
    let rc=await searchNoteBook({title:book_title});
    let notes=rc[0]['contents'];
    notes.forEach((item)=>{
        if(item.title===note_title){
            global.text=item.text;
        }
    })
}
const verifyNote=(req,res)=>{
    let arr = req.url.split('?');
    let url = querystring.parse(arr[1]);
    console.log(url);
    res.writeHead(200,'o98k',{'content-type':'text/plain;charset=utf-8'});
    res.end(JSON.stringify(url));
}
const deleteNote=(req,res)=>{
    let arr = req.url.split('?');
    let url = querystring.parse(arr[1]);
    console.log(url);
     let promise=new Promise(async(resolve,reject)=>{
        target_book=await searchNoteBook({'title':url.book_title});
        resolve('find_success');
    }).then(()=>{
        let after=target_book[0];
        for(let i=0;i<after.contents.length;++i){
            if(after.contents[i].title===url.note_title){
                after.contents[i]=after.contents[after.contents.length-1];
                after.contents.pop();
                break;
            }
        }
        console.log(after)
        updateNoteBook({'title':url.book_title},after);
        res.writeHead(200,'o98k',{'content-type':'text/plain;charset=utf-8'});
        res.end('success');
    })
}
const addTag=(req,res)=>{
    let arr = req.url.split('?');
    let url = querystring.parse(arr[1]);
    let promise=new Promise(async(resolve,reject)=>{
        target_book=await searchNoteBook({'title':url.book_title});
        resolve('find_success');
    }).then(()=>{
        let after=target_book[0];
        for(let i=0;i<after.contents.length;++i){
            if(after.contents[i].title===url.note_title){
                if(after.contents[i]['tags']===undefined){
                    let temp=[url.tag_name];
                    after.contents[i].tags=temp;
                }
                else after.contents[i].tags.push(url.tag_name)
                console.log(after.contents[i]);
                break;
            }
        }
        
        updateNoteBook({'title':url.book_title},after);
        res.writeHead(200,'o98k',{'content-type':'text/plain;charset=utf-8'});
        res.end('success');
    })
}
//导出成员
module.exports={
    create,
    update,
    openNotebook,
    addNote,
    viewNote,
    modifyNote,
    initNote,
    verifyNote,
    findNote,
    addTag,
    deleteNote
}